<script setup>
  const { proxy } = getCurrentInstance()
  import {
    GetCalendarAPI,
    GetTeamAPI,
    GetLineAPI,
    userSaaAPI,
  } from '@/api/system/team'
  import { TreeListAPI } from '@/api/common'

  const {
    scheduling_class_info, // 班组
  } = proxy.useDict('scheduling_class_info')
  /**
   * 传入数据
   */
  const props = defineProps({
    data: {
      type: Object,
      default: () => { },
    },
    title: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  })

  /**
   * 树结构
   */
  const dataTree = ref([])

  /**
   * 班组成员
   */
  const dataTeam = ref([])

  /**
   *班次下拉
   */
  const classesList = ref([])

  /**
   * 工厂日历
   */
  const calendarList = ref([])

  /**
   *线别
   */
  const lineList = ref([])

  /**
   * 用户
   */
  const userList = ref([])

  /**
   * 表单实例
   */
  const ruleFormRef = ref(null)
  /**
   * 列表枚举 */
  const column = ref([
    { label: '工厂日历', prop: 'calendarId', width: 'auto' },
    { label: '班次', prop: 'classes', width: 'auto' },
    { label: '线别', prop: 'lineId', width: 'auto' },
    { label: '是否开启', prop: 'isEnable', width: 'auto' },
  ])

  /**
   * 树结构枚举
   */
  const defaultProps = {
    children: 'children',
    label: 'categoryName',
    value: 'id',
  }
  // 表单字段
  const ruleForm = reactive({
    list: [],
  })

  /**
   * 表单校验
   */
  const rules = reactive({
    teamCode: [{ required: true, message: '请填写班组编码', trigger: 'change' }],
    teamName: [{ required: true, message: '请填写班组名称', trigger: 'change' }],
    teamMember: [
      { required: true, message: '请选择班组成员', trigger: 'change' },
    ],
  })

  /**
   * 提交方法
   */
  const submit = async () => {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return false
    if (ruleForm.list.length == 0) {
      proxy.errorMsg("至少选择一条明细");
      return false
    }
    console.log(ruleForm, ruleForm.list.length, 'ruleForm');
    ruleForm.teamMember = ruleForm.teamMember?.join(',')
    return ruleForm
  }

  /**
   * 初始化数据
   */
  const initData = () => {
    if (props.data?.id) {
      Object.keys(props.data).forEach(
        (itemKey) => (ruleForm[itemKey] = props.data[itemKey])
      )
      ruleForm.teamMember = ruleForm.teamMember?.split(',')
      console.log(ruleForm.list)
    }
  }

  /**
   * 日历
   */
  const getCalendar = async () => {
    try {
      const { data: res } = await GetCalendarAPI()
      calendarList.value = res
    } catch (err) {
      console.log(err)
    }
  }
  getCalendar()

  /**
   * 班次
   */
  const getTeam = async (id) => {
    try {
      const { data: res } = await GetTeamAPI({ calendarId: id })
      classesList.value = res
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * 线别
   */
  const getLine = async (id) => {
    try {
      const { data: res } = await TreeListAPI()
      lineList.value = res
    } catch (err) {
      console.log(err)
    }
  }

  /**
   * 选择日历
   */
  const getHand = (val) => {
    console.log(val, 'val')
    val.classesList = []
    val.lineList = []
    val.lineIdList = ''
    val.classes = ''
    let v = calendarList.value.filter((t) => {
      return t.calendarId == val.calendarId
    })[0]
    console.log(v, 'vv')
    val.classesList = v.classesList
    val.lineList = v.lineList
    console.log(val, 'val')

    // getTeam(id)
  }

  /**
   * 添加班别
   */
  const addList = () => {
    ruleForm.list.push({ isEnable: '1' })
  }

  /**
   * 用户 userList
   */
  const userSaa = async (id) => {
    try {
      const res = await userSaaAPI()
      userList.value = res.rows.map((t) => {
        return {
          label: t.nickName,
          value: t.userId,
          key: t.userId,
        }
      })
    } catch (err) {
      console.log(err)
    }
  }
  userSaa()
  /**
   * 回显数据赋值
   */
  initData()
  getLine()
  defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <!-- 新增 表单 -->
    <el-form :model="ruleForm" label-width="120px" :rules="rules" status-icon inline ref="ruleFormRef">
      <el-form-item label="班组编码" prop="teamCode">
        <el-input clearable v-model="ruleForm.teamCode" :disabled="props.title != '新增'" />
      </el-form-item>
      <el-form-item label="班组名称" prop="teamName">
        <el-input clearable v-model="ruleForm.teamName" :disabled="props.disabled" />
      </el-form-item>
      <el-form-item label="负责人">
        <p-select :option="userList" :disabled="props.disabled" clearable v-model="ruleForm.teamChargePerson"
          :placeholder="`请选择负责人`" />
      </el-form-item>

      <div class="rk">
        <el-form-item label="班组成员" prop="teamMember">
          <el-transfer v-model="ruleForm.teamMember" filterable filter-placeholder="班组成员" :data="userList" />
        </el-form-item>
      </div>
    </el-form>
    <div class="flex-items-center flex-between" style="width: 100%">
      <div class="title">班别设置：</div>
      <div class="flex-between" v-if="!props.disabled">
        <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
          <el-icon @click="addList">
            <Plus />
          </el-icon>
        </el-tooltip>
        <div style="margin: 0 10px"></div>
        <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
          <el-icon @click="ruleForm.list.pop()">
            <Minus />
          </el-icon>
        </el-tooltip>
      </div>
    </div>
    <p-table keyId="id" :column="column" stripe border :data="ruleForm.list" height="400" highlight-current-row
      @change="handleSelectionChange">
      <template #columnCell="{ column, record }">
        <!-- <p-select
          :option="calendarList"
          clearable
          v-if="column.label == '工厂日历'"
          v-model="record.calendarId"
          :placeholder="`请选择工厂日历`"
          :disabled="props.disabled"
          @change="getHand"
        /> -->
        <el-select v-model="record.calendarId" :disabled="props.disabled" placeholder="请选择工厂日历"
          v-if="column.label == '工厂日历'" style="width: 240px" @change="getHand(record)">
          <el-option v-for="item in calendarList" :key="item.calendarId" :label="item.calendarName"
            :value="item.calendarId" />
        </el-select>
        <el-select v-model="record.classes" :disabled="props.disabled" placeholder="请选择班次" v-if="column.label == '班次'"
          style="width: 240px">
          <el-option v-for="item in record.classesList" :key="item.classesId" :label="item.classesName"
            :value="item.classesId" />
        </el-select>
        <!-- <p-select
          :option="record.classesList"
          clearable
          v-if="column.label == '班次'"
          v-model="record.classes"
          :disabled="props.disabled"
          :placeholder="`请选择班次`"
        /> -->
        <el-cascader v-model="record.lineIdList" :options="record.lineList" :disabled="props.disabled" :props="{
            label: 'lineName',
            value: 'lineId',
            children: 'children',
          }" @change="handleChange" v-if="column.label == '线别'" />

        <!-- <p-switch
          v-if="column.label == '是否开启'"
          :v-model="record.isEnable"
          :disabled="props.disabled"
        /> -->
        <el-switch v-model="record.isEnable" v-if="column.label == '是否开启'" :disabled="props.disabled" active-value="0"
          inactive-value="1" />
      </template>
    </p-table>
  </div>
</template>
<style lang="scss" scoped>
  .rk ::v-deep .el-form-item {
    width: 100% !important;
  }
</style>